package com.bzkj.basicinfo.service.impl.ncc;

import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSON;
import com.bzkj.basicinfo.domain.ncc.NccMaterialAttribute;
import com.bzkj.basicinfo.mapper.NccMaterialAttributeMapper;
import com.bzkj.basicinfo.service.ncc.NccMaterialAttributeService;
import com.bzkj.basicinfo.utils.DataBatchProcessorUtil;
import com.bzkj.basicinfo.utils.HttpClientUtils;
import com.bzkj.common.core.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author swj
 * @desc ncc物料属性信息同步service实现类
 */
@Slf4j
@Service("nccJobMaterialAttributeService")
public class NccMaterialAttributeServiceImpl implements NccMaterialAttributeService {

    @Autowired
    private HttpClientUtils hcu;

    @Autowired
    private NccMaterialAttributeMapper nccMaterialAttributeMapper;

    @Value("${pk_org.code}")
    private Integer pkOrgCode;

    @Override
    public R jobBdDefDoclistMethodExecute() {
        LocalDateTime startOfDay = LocalDateTime.now()
                .withHour(0)
                .withMinute(0)
                .withSecond(0)
                .withNano(0);

        LocalDateTime endOfDay = LocalDateTime.now()
                .withHour(23)
                .withMinute(59)
                .withSecond(59)
                .withNano(999_999_999);
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String afterTime = endOfDay.format(pattern);
        String beforeTime = startOfDay.format(pattern);
        HttpResponse response = hcu.methodExecute(beforeTime, afterTime, "Bd_Material", "BT");
        com.alibaba.fastjson2.JSONObject jsonNode = JSON.parseObject(response.body());
        // 收集rep系统数据
        List<NccMaterialAttribute> list = jsonNode.getJSONArray("data").toJavaList(NccMaterialAttribute.class);
        if (!list.isEmpty()) {
            extractedBdList(list);
        }
        log.info("=========================【ncc_bd_defdoclist】表数据同步完成======================");
        return R.ok("同步成功");
    }

    @Override
    public R jobBdDefDocMethodExecute(Boolean flag) {
        HashMap<String, String> searchDate = DataBatchProcessorUtil.getSearchDate(flag);

        // 查询当前数据
        HttpResponse response = hcu.methodExecute(searchDate.get("startTimeStr"), searchDate.get("endTimeStr"), 19, pkOrgCode);
        com.alibaba.fastjson2.JSONObject jsonNode = JSON.parseObject(response.body());
        // 收集rep系统数据
        List<NccMaterialAttribute> list = jsonNode.getJSONArray("data").toJavaList(NccMaterialAttribute.class);
        if (!list.isEmpty()) {
            extractedPkList(list);
        }
        log.info("=========================【ncc_bd_defdoc】表数据同步完成======================");
        return R.ok("同步成功");
    }

    /**
     * 批量更新或者插入
     *
     * @Date 2024/12/11 14:17:12
     * @Param list
     */
    @Transactional(rollbackFor = Exception.class)
    public void extractedBdList(List<NccMaterialAttribute> list) {
        //收集主键数据
        List<String> pkMaterial = list.parallelStream().map(NccMaterialAttribute::getCode).collect(Collectors.toList());

        //查看已经存在的主键
        Set<String> existPkMaterialSet = nccMaterialAttributeMapper.findNccBdDefList(pkMaterial);
        //获取需要更新的数据
        list.parallelStream().filter(item -> existPkMaterialSet.contains(item.getCode())).forEach(item -> {
            nccMaterialAttributeMapper.updateNccBdDefDocList(item);
        });
        //需要新增的数据
        list.parallelStream().filter(item -> !existPkMaterialSet.contains(item.getCode())).forEach(item -> {
            nccMaterialAttributeMapper.insertNccBdDefDocList(item);
        });
    }

    /**
     * 批量更新或者插入
     *
     * @Date 2024/12/11 14:17:12
     * @Param list
     */
    @Transactional(rollbackFor = Exception.class)
    public void extractedPkList(List<NccMaterialAttribute> list) {
        for (NccMaterialAttribute nccMaterialAttribute : list) {
            nccMaterialAttributeMapper.insertOrUpdate(nccMaterialAttribute);
        }
    }
}
